from pydantic import BaseModel, validator
from datetime import date
from typing import Optional

class MedicineBase(BaseModel):
    """
    药品基础模型
    """
    medicine_name: str
    main_indications: str
    stock: int
    batch: int
    expiry_date: date
    supplier: str
    price: int
    unit: str

    @validator('stock')
    def validate_stock(cls, v):
        if v < 0:
            raise ValueError("库存不能为负数")
        return v

    @validator('price')
    def validate_price(cls, v):
        if v <= 0:
            raise ValueError("价格必须大于0")
        return v

    @validator('expiry_date')
    def validate_expiry_date(cls, v):
        if v < date.today():
            raise ValueError("过期日期不能是过去日期")
        return v

    def check(self):
        """
        验证模型数据
        """
        # Pydantic 会自动验证，此方法可保留作为额外验证
        pass

class MedicineCreate(MedicineBase):
    """
    创建药品的模型
    """
    pass

class MedicineUpdate(BaseModel):
    """
    更新药品的模型
    """
    medicine_name: Optional[str] = None
    main_indications: Optional[str] = None
    stock: Optional[int] = None
    batch: Optional[int] = None
    expiry_date: Optional[date] = None
    supplier: Optional[str] = None
    price: Optional[float] = None
    unit: Optional[str] = None

    def check(self):
        """
        验证更新数据
        """
        if self.stock is not None and self.stock < 0:
            raise ValueError("库存不能为负数")
        if self.price is not None and self.price <= 0:
            raise ValueError("价格必须大于0")
        if self.expiry_date is not None and self.expiry_date < date.today():
            raise ValueError("过期日期不能是过去日期")

class MedicineResponse(MedicineBase):
    """
    药品响应模型
    """
    ID: int

    class Config:
        from_attributes = True

class MedicineNameRequest(BaseModel):
    medicine_name: str